var express = require('express');
var router = express.Router();
var AdminToken = require('../db/user_tokens.js');
var adminDao = require('../dao/admin');
var adminRoutes = module.exports;

/**
 * 管理员登录
 * @param  account
 * @param  password
 *         url/admin/login
 */
adminRoutes.login = function(req, res) {
    var par = paramAll(req);
    var err = checkHasParam(par, ['account', 'password']).err;
    if(err) return res.json(new ERR(err, 400));
    par.password = encryPassword(par.password);
    adminDao.login(par, function(err, data){
        if (err) return res.json(new ERR(err, 400));
        data.uid = data.uid;
        data.name = data.name;
        data.isAdmin = true;
        data.role = data.role;
        AdminToken.onLogin(data ,function(err, token){
            if(err) return res.json(new ERR(err, 400));
            data.token = token;
            delete data.password;
            delete data.role;
            res.json(new PKG(data));
        });
    });
}
router.post('/login', adminRoutes.login);

module.exports = router;